import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { ChatMessage } from '../models/chat-message.model'
import { EmojiService } from './emoji.service'
import { GiftService } from './gift.service'
import { LiveService } from './live.service'

@Injectable()
export class ChatService {
  constructor(
    @InjectModel(ChatMessage.name) private chatMessageModel: Model<ChatMessage>,
    private readonly emojiService: EmojiService,
    private readonly giftService: GiftService,
    private readonly liveService: LiveService
  ) {}

  // 发送消息
  async sendMessage(userId: string, message: string, roomId: string) {
    // 处理表情包
    const processedMessage = await this.emojiService.processMessage(message)

    // 处理礼物
    const isGift = await this.giftService.checkIfGift(message)
    if (isGift) {
      await this.giftService.handleGift(userId, message, roomId)
      return
    }

    // 处理特殊指令
    if (message.startsWith('/')) {
      return this.handleCommand(userId, message, roomId)
    }

    // 保存消息
    const chatMessage = new this.chatMessageModel({
      userId,
      roomId,
      content: processedMessage,
      timestamp: new Date(),
    })

    await chatMessage.save()

    // 触发直播互动
    await this.liveService.handleChatInteraction(userId, roomId)

    return chatMessage
  }

  // 处理特殊指令
  private async handleCommand(userId: string, command: string, roomId: string) {
    const [cmd, ...args] = command.slice(1).split(' ')

    switch (cmd) {
      case '点歌':
        return this.liveService.requestSong(userId, args.join(' '), roomId)
      case '投票':
        return this.liveService.startVote(userId, args, roomId)
      case '抽奖':
        return this.liveService.startLottery(roomId)
      default:
        throw new Error('未知指令')
    }
  }

  // 获取历史消息
  async getHistory(roomId: string, limit = 100) {
    return this.chatMessageModel.find({ roomId }).sort({ timestamp: -1 }).limit(limit).exec()
  }

  // 获取热门表情
  async getPopularEmojis(roomId: string) {
    return this.emojiService.getPopularEmojis(roomId)
  }

  // 获取礼物排行榜
  async getGiftRanking(roomId: string) {
    return this.giftService.getRoomGiftRanking(roomId)
  }
}
